package net.imain.cloud.controller;

import net.imain.cloud.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author: uncle
 * @apdateTime: 2017-12-09 18:41
 */
@RestController
@RequestMapping(value = "/movie-ribbon/")
public class MovieRibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping(value = "/{id}")
    public User findById(@PathVariable(value = "id") Long id) {
        // 消费另外一个微服务的API                    http://spring.application.name/api
        return restTemplate.getForObject("http://service-user/user/" + id, User.class);
    }

    @GetMapping("/test")
    public String test() {
        /* user 随机，user2 轮询 */
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-user");
        System.out.println(serviceInstance.getServiceId() + ": " +
                serviceInstance.getHost() + " : " + serviceInstance.getPort());

        ServiceInstance serviceInstance2 = loadBalancerClient.choose("service-user2");
        System.out.println(serviceInstance2.getServiceId() + ": " +
                serviceInstance2.getHost() + " : " + serviceInstance2.getPort());

        return "success";
    }
}
/* 定制Ribbon Client */